<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function test() {
            'use strict';
            //浅克隆 更改新对象 原对象会跟着改 
            //深克隆 完全脱离原对象 两个没有任何关系
            let obj1 = { a: 0, b: { c: 0 } };
            let obj2 = Object.assign({}, obj1);
            console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}

            obj1.a = 1;
            console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
            console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}

            obj2.a = 2;
            console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
            console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 0}}

            obj2.b.c = 3;
            console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 3}}
            console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 3}}

            // Deep Clone
            obj1 = { a: 0, b: { c: 0 } };
            let obj3 = JSON.parse(JSON.stringify(obj1));
            obj1.a = 4;
            obj1.b.c = 4;
            console.log(JSON.stringify(obj3)); // { "a": 0, "b": { "c": 0}}

        }
        obj1 = { a: 0, b: { c: 0 } };
        let obj2 = {}
        function deepCopy(target, res) {
            if (target instanceof Object) {

                for (const k in res) {
                    const item = res[k];
                    if (item instanceof Array) {
                        target[k] = [];
                        deepCopy(target[k], item)
                    } else if (item instanceof Object) {
                        target[k] = {};
                        deepCopy(target[k], item)
                    } else {
                        target[k] = item
                    }
                }
            } else {
                throw new Error('传入参数类型错误')
            }
        }
        test();

    </script>

</body>

</html>